<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Book extends Model
{
    use HasFactory;

    /**
     * 可批量赋值的字段
     *
     * @var array
     */
    protected $fillable = [
        'title',
        'author',
        'publisher',
        'isbn',
        'category',
        'description',
        'image',
        'price',
    ];

    /**
     * 字段类型转换
     *
     * @var array
     */
    protected $casts = [
        'price' => 'decimal:2',
        'created_at' => 'datetime',
        'updated_at' => 'datetime',
    ];

    /**
     * 搜索查询作用域
     *
     * @param  \Illuminate\Database\Eloquent\Builder  $query
     * @param  string  $term
     * @return \Illuminate\Database\Eloquent\Builder
     */
    public function scopeSearch($query, $term)
    {
        return $query->where(function ($query) use ($term) {
            $query->where('title', 'like', '%' . $term . '%')
                  ->orWhere('author', 'like', '%' . $term . '%')
                  ->orWhere('isbn', 'like', '%' . $term . '%')
                  ->orWhere('category', 'like', '%' . $term . '%');
        });
    }

    /**
     * 按类别筛选的作用域
     *
     * @param  \Illuminate\Database\Eloquent\Builder  $query
     * @param  string  $category
     * @return \Illuminate\Database\Eloquent\Builder
     */
    public function scopeByCategory($query, $category)
    {
        return $query->where('category', $category);
    }

    /**
     * 获取格式化的价格
     *
     * @return string
     */
    public function getFormattedPriceAttribute()
    {
        return '¥' . number_format($this->price, 2);
    }
}
